package com.hxl.tech.gateway.auth.context;


import com.hxl.tech.gateway.auth.dto.UserInfo;
import com.hxl.tech.gateway.auth.exception.AuthException;
import com.hxl.tech.gateway.auth.util.HttpUtil;
import com.hxl.tech.gateway.auth.util.JwtUtil;
import com.hxl.tech.gateway.common.constant.AppConstant;
import com.hxl.tech.gateway.common.constant.Result;
import com.hxl.tech.gateway.common.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;


@Order(-1)
@Slf4j
public class ContextInterceptor implements HandlerInterceptor {

    private static final List<String> ignoreUris = Arrays.asList("/auth/echo", "/auth/static/", "/auth/doc.html",
            "/auth/favicon.ico","/auth/error", "/auth/webjars", "/auth/.well-known/jwks.json", "/auth/swagger-resources",
            "/auth/oauth/token", "/auth/oauth/authorize", "/auth/login","/auth/gateway.auth.user.login", "/auth/gateway.auth.sms.code.send", "/auth/gateway.auth.user.register"

            ,            "/auth/gateway.auth.merchant.app.login"
    );


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = HttpUtil.getURI(request);
        for (String ignoreUri : ignoreUris) {
            if (uri.startsWith(ignoreUri)) {
                return true;
            }
        }

        ContextHolder.clear();
        String token = HttpUtil.getToken(request);

        // 用户调用处理
        if (StringUtils.isBlank(token)) {
            log.debug("拦截uri："+uri);
            throw new AuthException(Result.E10006);
        }
        String redisKey = AppConstant.REDIS_USER_TOKEN + token;
        Object redisValue = RedisUtil.get(redisKey);
        if (Objects.isNull(redisValue) || !token.equals(redisValue.toString())) {
            throw new AuthException(Result.E10006);
        }

        String userId = JwtUtil.getKeyValue(token, "user_id");
        String userName = JwtUtil.getKeyValue(token, "user_name");
        String realName = JwtUtil.getKeyValue(token, "real_name");
        String roleName = JwtUtil.getKeyValue(token, "role_name");

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setUserName(userName);
        userInfo.setRealName(realName);
        userInfo.setRoleName(roleName);
        userInfo.setIsAdmin(AppConstant.ROLE_ADMIN.equals(roleName) ? true : false);
        userInfo.setIsDeveloper(!userInfo.getIsAdmin() ? true : false);
        ContextHolder.setUserInfo(userInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ContextHolder.clear();
    }
}
